package com.zy.gmall2020.orderservice.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.zy.gmall0401.bean.OrderInfo;
import com.zy.gmall0401.enums.ProcessStatus;
import com.zy.gmall0401.service.OrderService;
import com.zy.gmall0401.util.ActiveMQUtil;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Component
public class OrderConsumer {

    @Autowired
    ActiveMQUtil activeMQUtil;

    @Reference //dubbo
    OrderService orderService;
//    @Autowired //本地服务
//    OrderService orderService;
    /*
       订单模块消费支付MQ的消息
       PAYMENT_TO_ORDER *队列名称*
       jmsQueueListener  监听不到可能是扫描包名字不对在Gmall0401OrderServiceApplication
       上的@ComponentScan(basePackages = "com.zy") 所有用到包（范围）
     */
    @JmsListener(destination = "PAYMENT_TO_ORDER", containerFactory = "jmsQueueListener")
    public void consumePayment(MapMessage mapMessage) throws JMSException {
        String orderId = mapMessage.getString("orderId");
        String result = mapMessage.getString("result");//支付状态
        if ("success".equals(result)) {
            System.out.println("订单" + orderId + "支付完成");
            // 订单修改状态
            orderService.updateStatus(orderId, ProcessStatus.PAID);
            // 发送消息给库存系统
            sendOrderToWare(orderId);
        }

    }

    /*
      发送消息给库存系统锁库存使用发送到MQ
     */
    public void sendOrderToWare(String orderId) {
      // 把订单对象转换成Map
        Map paramMap = orderService.initWareParamJson(orderId);
        String wareParamJson = JSON.toJSONString(paramMap);
       // 把订单对象转换成Map发送到MQ的队列中去
        Connection connection = activeMQUtil.getConnection();
        try {
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            MessageProducer producer = session.createProducer(session.createQueue("ORDER_RESULT_QUEUE"));
            ActiveMQTextMessage textMessage = new ActiveMQTextMessage();
            textMessage.setText(wareParamJson);
            producer.send(textMessage);
            orderService.updateStatus(orderId, ProcessStatus.NOTIFIED_WARE);//更新订单状态为已发货
            session.commit();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }


    }

/*
  接受库存模块发送的MQ消息
  SKU_DEDUCT_QUEUE 接受队列消息锁库存或者（以减少库存）或者异常
 */
    @JmsListener(destination = "SKU_DEDUCT_QUEUE", containerFactory = "jmsQueueListener")
    public void consumeWareDeduct(MapMessage mapMessage) throws JMSException {
        // 更新订单状态
        String orderId = mapMessage.getString("orderId");
        String status = mapMessage.getString("status");
        if ("DEDUCTED".equals(status)) {
            orderService.updateStatus(orderId, ProcessStatus.WAITING_DELEVER);
        } else {
            orderService.updateStatus(orderId, ProcessStatus.STOCK_EXCEPTION);
        }

    }


    @JmsListener(destination = "SKU_DELIVER_QUEUE", containerFactory = "jmsQueueListener")
    public void consumeDeliver(MapMessage mapMessage) throws JMSException {
        String orderId = mapMessage.getString("orderId");
        String status = mapMessage.getString("status");
        String trackingNo = mapMessage.getString("trackingNo");

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTrackingNo(trackingNo);
        if (status.equals("DELEVERED")) {
            orderService.updateStatus(orderId, ProcessStatus.DELEVERED, orderInfo);
        }
        new ThreadPoolTaskExecutor();


        ScheduledExecutorService executorService;
        ExecutorService executorService1 = Executors.newFixedThreadPool(1);
    }
}
